/**
 * axios封装
 * 请求拦截、响应拦截、错误统一处理
 */
import axios from 'axios'
import router from '../router'
// import store from '../store/index'
import { Toast } from 'vant'
import homeApi from '@/api/homeApi'
import qs from 'qs'
// axios.defaults.withCredentials = false
const baseUrl = process.env.BASE_API
// eslint-disable-next-line valid-jsdoc
/**
 * 提示函数
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = msg => {
  Toast({
    message: msg,
    duration: 1000,
    forbidClick: true
  })
}

/**
 * 用户登录
 * 获取到userId后，做登录
 */
let promise = null
const toLogin = () => {
  let url = `${baseUrl}/proxy/sa/qywx/login?corp=zzpt-bkt&uri=${encodeURIComponent(window.location.origin)}${encodeURIComponent('/bkt/')}`
  window.location.href = url
}

// 创建axios实例
var instance = axios.create({ timeout: 60000 })
// 设置post请求头
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/**
 * 请求拦截器
 * 每次请求前，如果存在token则在请求头中携带token
 */

instance.interceptors.request.use(
  config => {
    let orgId = localStorage.getItem('orgId')
    let userId = localStorage.getItem('userId')
    let params = {}
    // let headerParams = {}
    if (config.method.toLowerCase() == 'post') {
      if (config.data) {
        if (config.data.extype == 1) {
          config.data = {
            name: config.data.name,
            carNo: config.data.carNo
          }
        } else {
          params = config.data
          if (localStorage.getItem('orgId')) {
            params.orgId = localStorage.getItem('orgId')
          }
          params.userId = userId
        }
      }
    } else if (config.method.toLowerCase() == 'get') {
      params = { ...config.params, orgId: '', userId: '' }
      if (orgId) {
        params.orgId = orgId
      }
      params.userId = userId
    }

    // if(params && params.headers){
    //   headerParams = params.headers
    //     delete params.headers
    // }
    let token = { satoken: localStorage.getItem('token') }

    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    // config.headers["Access-Control-Allow-Origin"]= "*";
    if (localStorage.getItem('token')) {
      config.headers = Object.assign({}, config.headers, token)
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  response => {
    // if ((!localStorage.getItem('UserId') || localStorage.getItem('UserId') == '') && goLogin) {
    //   getUserId()
    // }
    if (response.data.errorCode == 9999 || response.data.errorMessage == '用户未登录') {
      // 需要登录，且还没登录的存储已登录状态
      toLogin()
    }

    if (!response.data.success) {
      if (response.data.errorMessage && response.data.errorMessage == 'ConnectException: 拒绝连接 (Connection refused)') {
        Toast('金蝶CAM系统正在进行升级，请稍后再试~')
      } else if (response.data.errorMessage == '用户未登录') {
        Toast('用户未登录')
      }
      return response.data
    }
    if (response && response.data && response.data.data && response.data.data.code != 1) {
      // console.log('错误日志:', response.data);
      if (response.data.data.msg) {
        Toast(response.data.data.msg)
      }
      if (response.data.data.err) {
        Toast(response.data.data.err)
      }
      return response.data.data
    }

    return response.data.data
  },
  // 请求失败
  error => {
    if (error) {
      // console.log(error, '错误代码')
      if (error.response) {
        errorHandle(error.response.code, error.response.data)
      }
      return Promise.reject(error)
    } else {
      // 处理断网的情况
      // eg:请求超时或断网时，更新state的network状态
    }
  }
)

export default instance
